package com.gxa.employment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.employment.entity.dto.*;
import com.gxa.employment.entity.pojo.*;
import com.gxa.employment.entity.vo.PageVo;
import com.gxa.employment.entity.vo.StuClazzIvwVo;
import com.gxa.employment.mapper.ClazzMapper;
import com.gxa.employment.mapper.StudentMapper;
import com.gxa.employment.service.ClazzService;
import com.gxa.employment.service.MajorService;
import com.gxa.employment.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 班级信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-25
 */
@Transactional(rollbackFor = Throwable.class)
@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private MajorService majorService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;


    /**
     * 添加班级信息到数据库
     *
     * @param serviceAddListDto 包含班级信息的DTO对象
     * @return 如果添加成功返回true，否则返回false
     */
    @Override
    public Boolean addClazzBitch(List<ClazzServiceAddDto> serviceAddListDto) {
        // 创建一个新的ClazzAddListDto对象
        ClazzAddListDto clazzAddListDto = new ClazzAddListDto();

        // 遍历serviceAddListDto中的ClazzServiceAddDto列表
        for (ClazzServiceAddDto clazzAddDto : serviceAddListDto) {
            // 创建一个新的ClazzAddDto对象
            ClazzAddDto clazzAddDto1 = new ClazzAddDto();

            // 使用BeanUtils将clazzAddDto的属性复制到clazzAddDto1中
            BeanUtils.copyProperties(clazzAddDto, clazzAddDto1);

            // 计算clazzAddDto1的结束日期为开始日期加上天数
            clazzAddDto1.setClazzEnd(clazzAddDto.getClazzStart().plusDays(clazzAddDto.getClazzDays()));
            LambdaQueryWrapper<Major> userLambdaQueryWrapper = Wrappers.lambdaQuery(Major.class);

            // 设置查询条件：班级ID等于传入的clazzNotEmploymentDto中的班级ID

            userLambdaQueryWrapper.eq(Major::getMajorName, clazzAddDto.getMajorName());
                    // 设置查询条件：学生状态等于传入的clazzNotEmploymentDto中的学生状态


            Major one = majorService.getOne(userLambdaQueryWrapper);

            clazzAddDto1.setMajorId(one.getMajorId());

            // 将修改后的clazzAddDto1添加到clazzAddListDto的ClazzAddDto列表中
            clazzAddListDto.getClazzAddDtos().add(clazzAddDto1);


        }

        // 调用clazzMapper的insertClazzBitch方法，并判断返回值是否大于0
        return clazzMapper.insertClazzBitch(clazzAddListDto) > 0;
    }


    /**
     * 根据班级和学生状态进行分页查询
     *
     * @param clazzNotEmploymentDto 包含班级ID和学生状态的DTO对象
     * @return PageVo 分页查询结果封装对象
     */
    @Override
    public PageVo searchByClazzNotEmployment(ClazzNotEmploymentDto clazzNotEmploymentDto) {
        // 创建LambdaQueryWrapper对象，用于构建查询条件
        LambdaQueryWrapper<Student> userLambdaQueryWrapper = Wrappers.lambdaQuery(Student.class);

        // 设置查询条件：班级ID等于传入的clazzNotEmploymentDto中的班级ID
        userLambdaQueryWrapper.eq(Student::getClazzId, clazzNotEmploymentDto.getClazzId())
                // 设置查询条件：学生状态等于传入的clazzNotEmploymentDto中的学生状态
                .eq(Student::getStuStatus, clazzNotEmploymentDto.getStuStatus());

        // 创建IPage对象，用于分页查询，设置当前页码和每页显示的记录数
        IPage<Student> iPage = new Page<>(clazzNotEmploymentDto.getPage(), clazzNotEmploymentDto.getSize());

        // 调用studentService的page方法进行分页查询，传入分页信息和查询条件
        studentService.page(iPage, userLambdaQueryWrapper);


        // 创建PageVo对象，用于封装分页查询结果
        PageVo pageVo = new PageVo<>(iPage.getTotal(), iPage.getRecords());

        // 返回封装后的分页查询结果
        return pageVo;
    }




    /**
     * 更新班级更新理由
     *
     * @param clazzUpdateReasonDto 班级更新理由数据传输对象，包含需要更新的天数、理由和班级ID
     * @return 如果更新成功，则返回true；否则返回false
     */
    @Override
    public Boolean updateReason(ClazzUpdateReasonDto clazzUpdateReasonDto) {
        Clazz clazz = clazzMapper.selectById(clazzUpdateReasonDto.getClazzId());
        // 创建LambdaUpdateWrapper对象，用于构造更新条件
        LambdaUpdateWrapper<Clazz> lambdaUpdate = Wrappers.lambdaUpdate();
        if(!clazz.getClazzStatus().equals("结束")){
            lambdaUpdate
                    .set(Clazz::getClazzDays, clazzUpdateReasonDto.getDays()) // 设置班级天数
                    .set(Clazz::getClazzReason, clazzUpdateReasonDto.getReason()) // 设置班级理由
                    .set(Clazz::getUpdated, LocalDateTime.now()) // 设置更新时间为当前时间
                    .set(Clazz::getClazzEnd,clazz.getClazzStart().plusDays(clazzUpdateReasonDto.getDays()))
                    .eq(Clazz::getClazzId, clazzUpdateReasonDto.getClazzId()); // 设置更新条件为班级ID等于传入的班级ID

        }else {
            lambdaUpdate
                    .set(Clazz::getClazzDays, clazzUpdateReasonDto.getDays()) // 设置班级天数
                    .set(Clazz::getClazzReason, clazzUpdateReasonDto.getReason()) // 设置班级理由
                    .set(Clazz::getUpdated, LocalDateTime.now()) // 设置更新时间为当前时间
                    .set(Clazz::getClazzEnd,clazz.getClazzStart().plusDays(clazzUpdateReasonDto.getDays()))
                    .set(Clazz::getClazzStatus,"未完成")
                    .eq(Clazz::getClazzId, clazzUpdateReasonDto.getClazzId()); // 设置更新条件为班级ID等于传入的班级ID
        }
        // 设置更新的字段和对应的值
        // 执行更新操作，并返回更新影响的行数
        Integer update = clazzMapper.update(lambdaUpdate);

        // 判断更新影响的行数是否大于0，大于0表示更新成功，返回true；否则返回false
        return update > 0;
    }

    /**
     * 获取班级学生报告的分页信息
     *
     * @param clazzSearchDto 班级搜索条件，包括分页信息、查询条件等
     * @return 包含分页信息和查询结果的PageVo对象
     */
    @Override

    public PageVo getClazzStudentReport(ClazzSearchDto clazzSearchDto) {
        // 计算当前页的起始位置
        clazzSearchDto.setPage((clazzSearchDto.getPage()-1)*clazzSearchDto.getSize());

        // 从数据库中查询班级学生报告列表
        List<ClazzStudent> clazzStudentReport = clazzMapper.getClazzStudentReport(clazzSearchDto);

        // 从数据库中查询班级学生报告总数
        Long clazzStudentReportCount = clazzMapper.getClazzStudentReportCount(clazzSearchDto);

        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        PageVo pageVo=new PageVo<>();



        // 从 Redis 中获取是否修改了学生的就业状态
        String o = (String) operations.get("StudentStatus:");
        System.out.println("--------------------------------------------------------");
        System.out.println("修改后的状态"+o);
        //如果数据被修改过，则重新计算班级状态并更新数据库
        List<ClazzStudent> list = new ArrayList<>();
        List<ClazzNotEmploymentDto> stringList = new ArrayList<>();
        if (o==null){
            pageVo = new PageVo<>(clazzStudentReportCount, clazzStudentReport);
            return pageVo;

        }else {


            for (ClazzStudent clazzStudent : clazzStudentReport) {
//            String st = new String();
                ClazzNotEmploymentDto clazzNotEmploymentDto = new ClazzNotEmploymentDto();
                if (clazzStudent.getClazzStart().isAfter(LocalDate.now()) ){
                    clazzStudent.setClazzStatus("未开始");
                }else if (clazzStudent.getClazzStart().isBefore(LocalDate.now()) && clazzStudent.getClazzEnd().isAfter(LocalDate.now()) ){
                    List<Student> pageVo1 = getClazzStatus(new ClazzNotEmploymentDto(clazzStudent.getClazzId(), "未就业",1,5));
                    List<Student> pageVo2 = getClazzStatus(new ClazzNotEmploymentDto(clazzStudent.getClazzId(), "推迟",1,5));
                    List<Student> pageVo3 = getClazzStatus(new ClazzNotEmploymentDto(clazzStudent.getClazzId(), "推就业中",1,5));
                    List<Student> pageVo4 = getClazzStatus(new ClazzNotEmploymentDto(clazzStudent.getClazzId(), "就业中",1,5));
                    if (clazzStudent.getClazzEnd().isAfter(LocalDate.now())){
                        if ((pageVo1.size() > 0 || pageVo2.size() > 0 || pageVo3.size() > 0 || pageVo4.size() > 0)) {
//
                            clazzStudent.setClazzStatus("未完成");
                        }else {
//
                            clazzStudent.setClazzStatus("完成");
                        }
                    }
                }else if (clazzStudent.getClazzEnd().isBefore(LocalDate.now())){
                    clazzStudent.setClazzStatus("结束");
                }
                clazzNotEmploymentDto.setClazzId(clazzStudent.getClazzId());
                clazzNotEmploymentDto.setStuStatus(clazzStudent.getClazzStatus());
                stringList.add(clazzNotEmploymentDto);
                list.add(clazzStudent);
            }
            //批量修改
            System.out.println("修改的列表"+stringList);
            if (!stringList.isEmpty()) {
                Integer update = clazzMapper.updateClazzStatus(stringList);
            }

            // 创建并设置PageVo对象，包含分页信息和查询结果
            pageVo = new PageVo<>(clazzStudentReportCount, list);

        }
        redisTemplate.delete("StudentStatus:");
        System.out.println("--------------------------------------------------------");
        System.out.println("查询后的状态"+operations.get("StudentStatus:"));

        // 返回包含分页信息和查询结果的PageVo对象
        return pageVo;
    }

    /**
     * 获取班级就业详细信息
     * @return
     */
    @Override
    public List<ClazzEmpStu> getClazzEmploymentDetails() {
        // 获取班级就业详细信息
        return clazzMapper.getClazzEmploymentDetails();
    }

    @Override
    public PageVo searchStudent(ClazzSearchDto clazzSearchDto) {
        List<StuClazzIvwVo> student = clazzMapper.getStudent(clazzSearchDto);
        Long studentCount = Long.valueOf(clazzMapper.getStudentCount(clazzSearchDto));
        PageVo pageVo=new PageVo<>(studentCount,student);
        return pageVo;
    }

    @Override
    public PageVo searchNotStudent(ClazzSearchDto clazzSearchDto) {
        List<StuClazzIvwVo> student = clazzMapper.getNotStudent(clazzSearchDto);
        Long studentCount = Long.valueOf(clazzMapper.getNotStudentCount(clazzSearchDto));
        PageVo pageVo=new PageVo<>(studentCount,student);
        return pageVo;
    }

    @Override
    public List<Student> getClazzStatus(ClazzNotEmploymentDto clazzNotEmploymentDto) {
        LambdaQueryWrapper<Student> userLambdaQueryWrapper = Wrappers.lambdaQuery(Student.class);

        // 设置查询条件：班级ID等于传入的clazzNotEmploymentDto中的班级ID
        userLambdaQueryWrapper.eq(Student::getClazzId, clazzNotEmploymentDto.getClazzId())
                // 设置查询条件：学生状态等于传入的clazzNotEmploymentDto中的学生状态
                .eq(Student::getStuStatus, clazzNotEmploymentDto.getStuStatus());
        List<Student> students = studentMapper.selectList(userLambdaQueryWrapper);
        return students;

    }




}
